import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:reabampos/src/reabam/operation/bean/chengzhong/bean_chengzhong.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/utils/rb_color.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';
import 'package:xsdk_flutter_plugin/plugin/x_utils_flutter_plugin.dart';

/*
称重
 */
class ChengzhongStatePage extends XPageState {
  bool isOnXuzhong = false; //续重中,没开始下一次称重
  bool isManualChengzhong = false; //手动称重

  late Bean_Chengzhong value;

  String itemUnit = "kg";
  late List<BeanWeighValueData> presetGoodsWeighingList;

  double totalKg = 0;
  double eachKg = 0;
  late double dealPrice_kg;
  late double weighingNumber; //上1界面传入去皮重量
  bool isShowQupiyushe = false; //去皮预设

  // late Color RBColors.reabamColor4;

  ChengzhongStatePage(String json) {
    value = Bean_Chengzhong.fromJson(XJsonUtils.json2Map(json));

    presetGoodsWeighingList = value.presetGoodsWeighingList ?? [];

    if (presetGoodsWeighingList.isNotEmpty) {
      presetGoodsWeighingList[0].isUserSelect = true;
      weighingNumber = XNumberUtils.dynamic2double(
              presetGoodsWeighingList[0].weighingNumber) ??
          0.0;
      isShowQupiyushe = true;
    } else {
      weighingNumber = XNumberUtils.dynamic2double(value.weighingNumber) ?? 0.0;
    }

    dealPrice_kg = XNumberUtils.dynamic2double(value.price ?? '0') ?? 0;
  }

  @override
  Widget getBodyWidget(BuildContext context) {
    return XWidgetUtils.getLayoutContainer(
        backgroundColor: Colors.transparent,
        alignment: Alignment.center,
        child: XWidgetUtils.getXLayoutRoundedRect(
          padding: XWidgetUtils.getEdgeInsets(3, 3, 3, 3),
          width: 676,
          height: 470,
          backgroundColor: RBColors.reabamColor4,
          child: XWidgetUtils.getLayoutColumn(children: [
            //头部信息
            _getWidget_topBar(),
            XWidgetUtils.getLayoutExpanded(
                XWidgetUtils.getXLayoutRoundedRectWithBorder(
                    width: double.infinity,
                    borderWidth: 0,
                    radius_topRight: 0,
                    radius_topLeft: 0,
                    child: XWidgetUtils.getLayoutColumn(children: [
                      XWidgetUtils.getLayoutExpanded(
                          XWidgetUtils.getLayoutContainer(
                              child: XWidgetUtils.getLayoutColumn(children: [
                        //商品名称
                        _getWidget_itemName(),
                        //预设去皮
                        _getWidget_yushequpi(),
                        //总重量
                        _getWidget_zongzhongliang(),
                        //总金额
                        _getWidget_zongjine(),
                      ]))),
                      XWidgetUtils.getWidgetDivider(
                          marginRight: 0, marginLeft: 0),
                      //底部按钮
                      _getWidget_bottomBar(),
                    ])))
          ]),
        ));
  }

  //头部信息
  Widget _getWidget_topBar() {
    return XWidgetUtils.getLayoutContainer(
        height: 200,
        padding: XWidgetUtils.getEdgeInsets(0, 39, 0, 0),
        width: double.infinity,
        child: XWidgetUtils.getLayoutColumn(children: [
          XWidgetUtils.getLayoutRow(children: [
            XWidgetUtils.getLayoutContainer(
                width: 190,
                child: XWidgetUtils.getWidgetText('重量',
                    style: XStyleUtils.getTextStyle(
                        fontSize: 22, color: const Color(0xFFFFFFFF)),
                    padding: XWidgetUtils.getEdgeInsets(24, 0, 0, 0))),
            XWidgetUtils.getLayoutContainer(
                width: 256,
                child: XWidgetUtils.getWidgetText(
                  '单价(元/千克)',
                  style: XStyleUtils.getTextStyle(
                      fontSize: 22, color: const Color(0xFFFFFFFF)),
                )),
            XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetText(
              '金额',
              style: XStyleUtils.getTextStyle(
                  fontSize: 22, color: const Color(0xFFFFFFFF)),
            )),
          ]),
          XWidgetUtils.getLayoutContainer(height: 27),
          XWidgetUtils.getLayoutRow(children: [
            XWidgetUtils.getLayoutContainer(
                width: 190,
                child: XWidgetUtils.getWidgetText(
                    '${XNumberUtils.d2d(3, eachKg)}',
                    style: XStyleUtils.getTextStyle(
                        fontSize: 30, color: const Color(0xFFFFFFFF)),
                    padding: XWidgetUtils.getEdgeInsets(24, 0, 0, 0))),
            XWidgetUtils.getLayoutContainer(
              width: 256,
              padding: XWidgetUtils.getEdgeInsets(0, 0, 94, 0),
              child: XWidgetUtils.getXLayoutRoundedRectWithBorder(
                  alignment: Alignment.centerLeft,
                  borderColor: const Color(0xFFFFFFFF),
                  padding: XWidgetUtils.getEdgeInsets(10, 0, 10, 0),
                  radius_topLeft: 5,
                  radius_topRight: 5,
                  radius_bottomLeft: 5,
                  radius_bottomRight: 5,
                  backgroundColor: Colors.transparent,
                  child: XWidgetUtils.getWidgetText(
                    '${XNumberUtils.d2d(2, dealPrice_kg)}',
                    style: XStyleUtils.getTextStyle(
                        fontSize: 30, color: const Color(0xFFFFFFFF)),
                  )),
            ),
            XWidgetUtils.getLayoutExpanded(
                XWidgetUtils.getWidgetGestureDetector(
                    child: XWidgetUtils.getWidgetText(
                      '${XNumberUtils.formatDoubleN(2, eachKg * dealPrice_kg)}',
                      style: XStyleUtils.getTextStyle(
                          fontSize: 30, color: const Color(0xFFFFFFFF)),
                    ),
                    onTap: () {
                      setState(() {
                        isManualChengzhong = true;
                        startPage(
                            XPageStateCustomKeyboardNumberInputLandscape(
                                title: '修改金额',
                                limitXiaoshu: 2,
                                btSubmitColor: RBColors.reabamColor4),
                            resultCallback: (dynamic result) {
                          if (result != null) {
                            XLogUtils.printLog('---手工输入=$result');
                            setState(() {
                              totalKg = 0;
                              eachKg = result / dealPrice_kg;
                            });
                          }
                        });
                      });
                    })),
          ]),
        ]));
  }

  //底部按钮
  Widget _getWidget_bottomBar() {
    return XWidgetUtils.getLayoutContainer(
        height: 38,
        margin: XWidgetUtils.getEdgeInsets(0, 10, 0, 10),
        child: XWidgetUtils.getLayoutRow(children: [
          XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetGestureDetector(
              child: XWidgetUtils.getLayoutContainer(
                  backgroundColor: Colors.white,
                  alignment: Alignment.center,
                  child: XWidgetUtils.getWidgetText('取消',
                      style: XStyleUtils.getTextStyle(
                        fontSize: 18,
                        color: RBColors.reabamColor4,
                      ))),
              onTap: () {
                finishPage();
              })),
          XWidgetUtils.getWidgetDividerVertical(
              marginLeft: 0, marginRight: 0, height: 38),
          XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetGestureDetector(
              child: XWidgetUtils.getLayoutContainer(
                  backgroundColor: Colors.white,
                  alignment: Alignment.center,
                  child: XWidgetUtils.getWidgetText('手工输入',
                      style: XStyleUtils.getTextStyle(
                        fontSize: 18,
                        color: RBColors.reabamColor4,
                      ))),
              onTap: () {
                setState(() {
                  isManualChengzhong = true;
                  startPage(
                      XPageStateCustomKeyboardNumberInputLandscape(
                          title: '修改重量', btSubmitColor: RBColors.reabamColor4),
                      resultCallback: (dynamic result) {
                    if (result != null) {
                      setState(() {
                        XLogUtils.printLog('---手工输入=$result');
                        totalKg = 0;
                        eachKg = result;
                      });
                    }
                  });
                });
              })),
          XWidgetUtils.getWidgetDividerVertical(
              marginLeft: 0, marginRight: 0, height: 38),
          XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetGestureDetector(
              child: XWidgetUtils.getLayoutContainer(
                  backgroundColor: Colors.white,
                  alignment: Alignment.center,
                  child: XWidgetUtils.getWidgetText('续重',
                      style: XStyleUtils.getTextStyle(
                        fontSize: 18,
                        color: RBColors.reabamColor4,
                      ))),
              onTap: () {
                if (!isOnXuzhong) {
                  isOnXuzhong = true;
                  setState(() {
                    totalKg = totalKg + eachKg;
                    eachKg = 0;
                  });
                }
              })),
          XWidgetUtils.getWidgetDividerVertical(
              marginLeft: 0, marginRight: 0, height: 38),
          XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetGestureDetector(
              child: XWidgetUtils.getLayoutContainer(
                  backgroundColor: Colors.white,
                  alignment: Alignment.center,
                  child: XWidgetUtils.getWidgetText('置零',
                      style: XStyleUtils.getTextStyle(
                        fontSize: 18,
                        color: RBColors.reabamColor4,
                      ))),
              onTap: () {
                setState(() {
                  isOnXuzhong = false;
                  isManualChengzhong = false;
                  totalKg = 0;
                  eachKg = 0;
                });
              })),
          XWidgetUtils.getWidgetDividerVertical(
              marginLeft: 0, marginRight: 0, height: 38),
          XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetGestureDetector(
              child: XWidgetUtils.getLayoutContainer(
                  backgroundColor: Colors.white,
                  alignment: Alignment.center,
                  child: XWidgetUtils.getWidgetText('确认',
                      style: XStyleUtils.getTextStyle(
                        fontSize: 18,
                        color: RBColors.reabamColor4,
                      ))),
              onTap: () {
                if (totalKg + eachKg > 0) {
                  finishPage(result: totalKg + eachKg);
                } else {
                  toast("请放商品称重");
                }
              })),
        ]));
  }

  //总重量
  Widget _getWidget_zongzhongliang() {
    return XWidgetUtils.getLayoutContainer(
        margin: XWidgetUtils.getEdgeInsets(0, 0, 0, 10),
        child: XWidgetUtils.getLayoutRow(children: [
          XWidgetUtils.getWidgetText('总重量:',
              style: XStyleUtils.textStyle_666_18(),
              padding: XWidgetUtils.getEdgeInsets(24, 0, 0, 0)),
          XWidgetUtils.getWidgetText(
              '${XNumberUtils.d2d(3, (totalKg + eachKg))}',
              style: XStyleUtils.textStyle_000_18(),
              padding: XWidgetUtils.getEdgeInsets(28, 0, 0, 0)),
          const Spacer(),
          XWidgetUtils.getLayoutContainer(
              width: 100,
              margin: XWidgetUtils.getEdgeInsets(0, 0, 10, 0),
              child: XWidgetUtils.getWidgetText('手工去皮:',
                  textAlign: TextAlign.end,
                  style: XStyleUtils.textStyle_666_18())),
          XWidgetUtils.getWidgetGestureDetector(
              child: XWidgetUtils.getXLayoutRoundedRectWithBorder(
                width: 100,
                height: 26,
                radius_topLeft: 5,
                radius_topRight: 5,
                radius_bottomRight: 5,
                radius_bottomLeft: 5,
                margin: XWidgetUtils.getEdgeInsets(0, 0, 24, 0),
                padding: XWidgetUtils.getEdgeInsets(10, 0, 10, 0),
                child: XWidgetUtils.getWidgetText(
                    '${XNumberUtils.d2d(3, weighingNumber)}',
                    style: XStyleUtils.textStyle_000_18()),
              ),
              onTap: () {
                startPage(
                    XPageStateCustomKeyboardNumberInputLandscape(
                        title: '修改去皮重量', btSubmitColor: RBColors.reabamColor4),
                    resultCallback: (dynamic result) {
                  if (result != null) {
                    XLogUtils.printLog('---手工去皮=$result');
                    setState(() {
                      weighingNumber = result;
                    });
                  }
                });
              }),
        ]));
  }

  //总金额
  Widget _getWidget_zongjine() {
    return XWidgetUtils.getLayoutRow(children: [
      XWidgetUtils.getWidgetText('整单金额:',
          style: XStyleUtils.textStyle_666_18(),
          padding: XWidgetUtils.getEdgeInsets(24, 0, 0, 0)),
      XWidgetUtils.getWidgetText(
          '${XNumberUtils.formatDoubleN(2, (totalKg + eachKg) * dealPrice_kg)}',
          style: XStyleUtils.textStyle_000_18(),
          padding: XWidgetUtils.getEdgeInsets(10, 0, 0, 0)),
      const Spacer(),
      XWidgetUtils.getWidgetGestureDetector(
          child: XWidgetUtils.getXLayoutRoundedRectWithBorder(
            width: 100,
            height: 26,
            radius_topLeft: 5,
            radius_topRight: 5,
            radius_bottomRight: 5,
            radius_bottomLeft: 5,
            alignment: Alignment.center,
            borderColor: RBColors.reabamColor4,
            margin: XWidgetUtils.getEdgeInsets(0, 0, 10, 0),
            child: XWidgetUtils.getWidgetText('一键去皮',
                style: XStyleUtils.getTextStyle(
                    fontSize: 14, color: RBColors.reabamColor4)),
          ),
          onTap: () {
            setState(() {
              //当前所秤重量
              weighingNumber = eachKg;
            });
          }),
      XWidgetUtils.getWidgetGestureDetector(
          child: XWidgetUtils.getXLayoutRoundedRectWithBorder(
            width: 100,
            height: 26,
            radius_topLeft: 5,
            radius_topRight: 5,
            radius_bottomRight: 5,
            radius_bottomLeft: 5,
            alignment: Alignment.center,
            borderColor: RBColors.reabamColor4,
            margin: XWidgetUtils.getEdgeInsets(0, 0, 24, 0),
            child: XWidgetUtils.getWidgetText('清除去皮',
                style: XStyleUtils.getTextStyle(
                    fontSize: 14, color: RBColors.reabamColor4)),
          ),
          onTap: () {
            setState(() {
              weighingNumber = 0;
            });
          }),
    ]);
  }

  //商品名称
  Widget _getWidget_itemName() {
    return XWidgetUtils.getWidgetText('${value.itemName}',
        style: XStyleUtils.textStyle_000_18(),
        padding: XWidgetUtils.getEdgeInsets(24, 24, 24, 10));
  }

  //预设去皮widget
  Widget _getWidget_yushequpi() {
    return !isShowQupiyushe
        ? XWidgetUtils.getLayoutContainer(height: 60)
        : XWidgetUtils.getLayoutContainer(
            height: 60,
            child: XWidgetUtils.getLayoutRow(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  XWidgetUtils.getWidgetText('去皮预设:',
                      style: XStyleUtils.textStyle_666_18(),
                      padding: XWidgetUtils.getEdgeInsets(24, 0, 5, 0)),
                  XWidgetUtils.getLayoutExpanded(XWidgetUtils.getLayoutWrap(
                      itemData: presetGoodsWeighingList,
                      listItemWidgetFunction: (dynamic result) {
                        //
                        BeanWeighValueData iitem = result;
                        //
                        return XWidgetUtils.getWidgetGestureDetector(
                            child: XWidgetUtils.getXLayoutRoundedRectWithBorder(
                                radius_topLeft: 10,
                                radius_topRight: 10,
                                radius_bottomRight: 10,
                                radius_bottomLeft: 10,
                                backgroundColor: Colors.white,
                                alignment: Alignment.center,
                                margin: XWidgetUtils.getEdgeInsets(5, 0, 5, 5),
                                height: 24,
                                width: '${iitem.weighingName}'.length * 16 + 20,
                                borderColor: iitem.isUserSelect
                                    ? RBColors.reabamColor4
                                    : XColorUtils.colorCCCCCC,
                                child: XWidgetUtils.getWidgetText(
                                    '${iitem.weighingName}',
                                    style: XStyleUtils.getTextStyle(
                                        fontSize: 14,
                                        color: iitem.isUserSelect
                                            ? RBColors.reabamColor4
                                            : XColorUtils.colorCCCCCC))),
                            onTap: () {
                              if (!iitem.isUserSelect) {
                                setState(() {
                                  for (BeanWeighValueData sItem
                                      in presetGoodsWeighingList) {
                                    sItem.isUserSelect = false;
                                  }
                                  iitem.isUserSelect = true;
                                  weighingNumber = iitem.weighingNumber ?? 0;
                                });
                              }
                            });
                      })),
                ]));
  }

  @override
  Color getXPageBackgroundColor() {
    return Colors.black54;
  }

  @override
  void onStart() async {
    if (XFlutterUtils.isAndroid()) {
      Map<String, dynamic> deviceInfo = await XFlutterUtils.getDeviceInfo();
      String brand = deviceInfo['brand'];
      String model = deviceInfo['model'];
      XLogUtils.printLog(
          "---设备brand:$brand,model:$model"); //设备brand:SUNMI,model:T2s
      //串口电子秤
      if ((RBConfigs.isShangMiDevice && RBConfigs.isUserShangMiSerialWeigher) ||
          model == 'ZhiQ-R68P') {
        //中崎收银电子秤一体机,商米内置串口电子秤
        _connentWeigher_serial(model);
      } else {
        //手机,平板 usb串口电子秤
        _connentWeigher_usb_ble();
      }
    }
  }

  //连接电子秤:商米串口 {"type":"weigher","data":"0.28"}
  void _connentWeigher_serial(String model) {
    if ('T2s' == model) {
      XFlutterPluginUtils.serialPortConnect('SUNMI_T2s');
    } else if ('T2' == model) {
      XFlutterPluginUtils.serialPortConnect('SUNMI_T2');
    } else if ('D2_d_2nd' == model) {
      XFlutterPluginUtils.serialPortConnect('SUNMI_D2');
    } else if ('ZhiQ-R68P' == model) {
      XFlutterPluginUtils.serialPortConnect('ZhiQ-R68P');
    } else {
      XFlutterPluginUtils.serialPortConnect('SUNMI_T1');
    }

    //接收原生通知 {"type":"weigher","data":"0.295"}
    XFlutterPluginUtils.setReceiveNativeMessageCallback((resultMap) {
      XLogUtils.printLog("---电子秤json=$resultMap");
      String type = resultMap['type'] ?? '';
      if ("weigher" == type) {
        double? hr = XNumberUtils.dynamic2double(resultMap['data']);
        //处理电子秤返回值
        _handleWeigherValue(hr);
      }
    });
  }

  //连接电子秤:usb,蓝牙
  XBaseDevice? weigher_usb;
  void _connentWeigher_usb_ble() {
    //1.优先usb串口电子秤
    Set<XBaseDevice> usbDeviceList = XUsbSerialUtils.usbSerialDeviceList;
    for (XBaseDevice item in usbDeviceList) {
      if (RBConfigs.UsbSerialWeigher == item.customType) {
        weigher_usb = item;
        break;
      }
    }
    if (weigher_usb != null) {
      XUsbSerialUtils.connectUsbSerialDevice(
          device: weigher_usb!,
          callback: (Uint8List? result) {
            if (result != null) {
              String r = XStringUtils.uint8ListToString_gbk(result,
                      allowMalformed: true)
                  .trim();
              double? hr = RBBaseApi.handleWeigherResultToDouble(
                  weigher_usb!.brand ?? '', r);
              //处理电子秤返回值
              _handleWeigherValue(hr);
            }
          });
    } else {
      //2.蓝牙电子秤
    }
  }

  //处理电子秤返回值
  void _handleWeigherValue(double? value) {
    if (value != null) {
      if (isManualChengzhong) {
        //手动称重忽略
      } else {
        //非手动称重

        if (isOnXuzhong) {
          //续重中,忽略称重,
          //解除续重中状态,重新开始下一个称重
          if (value == 0) {
            setState(() {
              eachKg = 0;
              isOnXuzhong = false;
            });
          }
        } else {
          //非续重中
          if (eachKg != value - weighingNumber) {
            setState(() {
              eachKg = value - weighingNumber;
            });
          }
        }
      }
    }
  }

  @override
  Future<void> updateData({int pageIndex = 1}) async {}

  @override
  void onDestroy() {
    super.onDestroy();
    if (XFlutterUtils.isAndroid()) {
      XUsbSerialUtils.disconnectUsbSerialDevice();
      XFlutterPluginUtils.serialPortConnect('serial_disconnect');
    }
  }
}
